/* eslint-disable react-hooks/exhaustive-deps */
import { FC, useEffect, useMemo, useRef, useState } from 'react'
import QuestionCard from '../../components/QuestionCard'
import { Empty, Spin, Typography } from 'antd'
import styles from './common.module.scss'
import ListSearch from '../../components/ListSearch'
import { useSearchParams } from 'react-router-dom'
import { useDebounceFn, useRequest } from 'ahooks'
import { getQuestionListService } from '../../services/question'
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from '../../constants'

const { Title } = Typography

const List: FC = () => {
  const [searchParams] = useSearchParams()

  const [started, setStarted] = useState(false)
  const [questionList, setQuestionList] = useState([])
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const haveMoreData = total > questionList.length

  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''

  useEffect(() => {
    setStarted(false)
    setPage(1)
    setQuestionList([])
    setTotal(0)
  }, [keyword])

  const { run: load, loading } = useRequest(
    async () => {
      return await getQuestionListService({
        page,
        pageSize: LIST_PAGE_SIZE,
        keyword,
      })
    },
    {
      manual: true,
      onSuccess: data => {
        const { list, total } = data
        setQuestionList(prev => prev.concat(list))
        setTotal(total)
        setPage(page + 1)
      },
    }
  )

  const containerRef = useRef<HTMLDivElement>(null)
  // 触发加载的函数
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const elem = containerRef.current
      if (elem == null) return

      const domRect = elem.getBoundingClientRect()
      if (domRect == null) return

      const { bottom } = domRect

      if (bottom <= document.body.clientHeight) {
        load()
        setStarted(true)
      }
    },
    { wait: 500 }
  )

  useEffect(() => {
    tryLoadMore()
  }, [searchParams])

  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener('scroll', tryLoadMore)
    }

    return () => {
      window.removeEventListener('scroll', tryLoadMore)
    }
  }, [searchParams, haveMoreData])

  const loadMoreContentElem = useMemo(() => {
    if (loading || !started)
      return (
        <div style={{ textAlign: 'center' }}>
          <Spin />
        </div>
      )

    if (total === 0) return <Empty description="暂无数据" />

    if (!haveMoreData) return <span>没有更多了......</span>

    return <span>开始加载下一页</span>
  }, [loading, started, total, haveMoreData])

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {questionList?.length > 0 &&
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          questionList.map((p: any) => {
            const { _id: id } = p
            return <QuestionCard key={id} {...p} />
          })}
      </div>
      <div className={styles.footer}>
        <div ref={containerRef}>{loadMoreContentElem}</div>
      </div>
    </>
  )
}

export default List
